const app = getApp()

Page({
  data: {
    status: '',
    statusText: '',
    orders: [],
    loading: false
  },

  onLoad(options) {
    if (options.status && options.statusText) {
      this.setData({
        status: options.status,
        statusText: options.statusText
      });
      wx.setNavigationBarTitle({
        title: options.statusText
      });
    }
    this.loadOrders();
  },

  onShow() {
    this.loadOrders();
  },

  async loadOrders() {
    const technicianInfo = wx.getStorageSync('technicianInfo');
    if (!technicianInfo || !technicianInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });
    try {
      const res = await app.request({
        url: '/api/orders',
        method: 'GET'
      });

      let filteredOrders = res.data.filter(order => 
        order.technicianId === technicianInfo.id
      );
      // 定义状态映射
      const statusMap = {
        CONFIRMED: ['CONFIRMED', 'PENDING'], // 待处理
        PROCESSING: ['PROCESSING'],          // 进行中
        COMPLETED: ['COMPLETED']             // 已完成
      };
      if (this.data.status && this.data.status !== 'ALL') {
        const validStatuses = statusMap[this.data.status] || [this.data.status];
        filteredOrders = filteredOrders.filter(order => validStatuses.includes((order.status || '').toUpperCase()));
      }

      // 如果是待评价状态，需要额外过滤已完成但未评价的订单
      if (this.data.status === 'REVIEW') {
        filteredOrders = filteredOrders.filter(order => !order.review);
      }

      // 收集所有订单的userId
      const userIds = Array.from(new Set(filteredOrders.map(order => order.userId).filter(Boolean)));
      let userNicknames = {};
      if (userIds.length > 0) {
        // 并发请求所有用户信息
        const nicknameResults = await Promise.all(userIds.map(async (uid) => {
          try {
            const res = await app.request({
              url: `/api/users/${uid}`,
              method: 'GET'
            });
            return { uid, nickname: res.data && (res.data.nickname || res.data.username || '未知') };
          } catch (e) {
            return { uid, nickname: '未知' };
          }
        }));
        nicknameResults.forEach(item => {
          userNicknames[item.uid] = item.nickname;
        });
      }

      // 格式化订单数据，客户姓名用nickname
      const formattedOrders = filteredOrders.map(order => ({
        ...order,
        appointmentTime: order.appointmentTime ? order.appointmentTime.replace('T', ' ').slice(0, 16) : '',
        statusText: this.getStatusText(order.status),
        userName: userNicknames[order.userId] || '未知',
        userPhone: order.contactInfo || '未知',
        address: order.location || '未知',
        serviceType: `${order.deviceType || ''} - ${order.problemType || ''}`.trim()
      }));

      this.setData({
        orders: formattedOrders,
        loading: false
      });
    } catch (error) {
      console.error('加载订单失败：', error);
      wx.showToast({
        title: '加载订单失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  getStatusText(status) {
    const statusMap = {
      'PENDING': '待确认',
      'CONFIRMED': '待处理',
      'PROCESSING': '进行中',
      'COMPLETED': '已完成',
      'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
  },

  // 查看订单详情
  goToOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?id=${orderId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrders().then(() => {
      wx.stopPullDownRefresh();
    });
  }
}); 